<template>
  <div>
    <div class="search">
      <input v-model="keyWord" class="search-input" type="text" placeholder="输入城市名或拼音" />
    </div>
    <div class="searchList wrapper" v-show='keyWord'  ref='search'>
      <ul>
        <li
          class="search-item border-bottom"
          v-for="item of cityList"
          :key="item.id"
           @click="sendCity(item.name)"
        >{{ item.name }}</li>
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  // 组件名称
  name: "demo", // 组件参数 接收来自父组件的数据
  props: ["cities"],
  components: {},
  data() {
    return {
      keyWord: "",
      cityList: []
    };
  },
  computed: {
    hasNoData() {
      return !this.cityList.length;
    }
  },
  watch: {
    keyWord() {
      if (!this.keyWord) {
        this.cityList = [];
        return;
      }
      var result = []
      for (var i in this.cities) {
        this.cities[i].forEach(item => {
          if (
            item.name.indexOf(this.keyWord) > -1 ||
            item.spell.indexOf(this.keyWord) > -1
          ) {
            // this.cityList.push(item);
            result.push(item)
          }
        });
      }
      this.cityList = result
    }
    // keyword() {
    //   if (!this.keyword) {
    //     this.cityList = [];
    //     return;
    //   }
    //   //函数节流
    //   if (this.timer) {
    //     clearTimeout(this.timer);
    //   }

    //   this.timer = setTimeout(() => {
    //     const result = [];
    //     for (let i in this.cities) {
    //       this.cities[i].forEach(value => {
    //         //如果我们能从name  spell当中搜索到 我们就把它添加到result当中
    //         if (
    //           value.spell.indexOf(this.keyword) > -1 ||
    //           value.name.indexOf(this.keyword) > -1
    //         ) {
    //           result.push(value);
    //         }
    //       });
    //     }
    //     this.cityList = result;
    //   }, 100);
    // }
  },
  methods: {
    sendCity(city){
      this.$router.push('/')
      this.$store.commit('changeCity',city)
    }
  },
  beforeCreate() {},
  created() {},
  beforeMount() {},
  mounted() {
    //搜索出来内容的滚动
    this.Bscroll = new Bscroll(this.$refs.search);
  }
};
</script> 
<style lang="stylus" scoped>
.search {
  height: 0.72rem;
  padding: 0 0.1rem;
  background: #0088dd;

  .search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    padding: 0 0.1rem;
    line-height: 0.62rem;
    text-align: center;
    border-radius: 0.06rem;
    color: #666;
  }
}
.searchList
        z-index: 1
        overflow: hidden
        position: absolute
        top: 1.58rem
        left: 0
        right: 0
        bottom: 0
        background: #fff
        .search-item
            line-height: .62rem
            padding-left: .2rem
            background: #fff
            color: #666

</style>
